package com.leyou.cart.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired  //对象的k-v操作全程必须string
    private StringRedisTemplate redisTemplate;

    static final String KEY_PREFIX = "ly:cart:uid:";

    //要根据用户的id取得购物车信息
    public void addCart(Cart cart) {
        Long userId = cart.getUserId();
        //根据用户的id获取到这个Redis信息，ops就是我们第二层map
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        //对应的skuid，对应的tostring的json值，有可能为空
        Object value = ops.get(cart.getSkuId().toString());
        if (null == value) {//此商品的第一次添加
            ops.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));

        } else {
            //已经加过，改数量
            Cart storeCart = JsonUtils.nativeRead(value.toString(), new TypeReference<Cart>() {
            });
            storeCart.setNum(storeCart.getNum() + cart.getNum());
            //覆盖保存
            ops.put(cart.getSkuId().toString(), JsonUtils.serialize(storeCart));
        }
    }

    public List<Cart> queryCartsByUserId(Long userId) {
        //根据用户的id获取到这个Redis信息，ops就是我们第二层map
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(KEY_PREFIX + userId);

        List<Object> carts = ops.values();
        List<Cart> cartList = new ArrayList<>();

        // 判断是否有数据
        if (null != carts) {
            for (Object cart : carts) {
                cartList.add(JsonUtils.nativeRead(cart.toString(), new TypeReference<Cart>() {
                }));

            }
            return cartList;

        }
        return null;
    }

    public void updateCart(Long userId, Long skuId) {
        //根据用户的id获取到这个Redis信息，ops就是我们第二层map
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        Object skuJson = ops.get(skuId.toString());

        Cart cart = JsonUtils.nativeRead(skuJson.toString(), new TypeReference<Cart>() {
        });

        cart.setNum(cart.getNum() + 1);

        //改完后重新保存
        ops.put(skuId.toString(), JsonUtils.serialize(cart));


    }

    public void deleteCart(Long userId, Long skuId) {

        //根据用户的id获取到这个Redis信息，ops就是我们第二层map
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(KEY_PREFIX + userId);
        ops.delete(skuId.toString());

    }
}
